<template>
  <div class="project-detail-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-button type="text" @click="goBack">
              <el-icon><ArrowLeft /></el-icon> 返回列表
            </el-button>
            <h2 class="project-title">{{ project.title }}</h2>
            <el-tag :type="getStatusType(project.status)" class="status-tag">
              {{ getStatusText(project.status) }}
            </el-tag>
          </div>
          <div class="header-actions">
            <el-button 
              v-if="project.status === 1 && project.auditStatus === 1"
              type="primary" 
              @click="handleJoin">
              报名参加
            </el-button>
            <el-button 
              v-if="project.status === 2"
              type="success" 
              @click="handleSign">
              签到
            </el-button>
            <el-button 
              v-if="project.status === 2"
              type="warning" 
              @click="handleRecordHours">
              登记时长
            </el-button>
            <el-button 
              v-if="project.status === 1 || project.status === 2"
              type="danger" 
              @click="handleQuit">
              退出项目
            </el-button>
          </div>
        </div>
      </template>

      <div class="project-content" v-if="!loading">
        <!-- 项目基本信息 -->
        <el-row :gutter="20">
          <el-col :span="16">
            <div class="project-info">
              <div class="project-image-container">
                <el-image 
                  :src="project.image || 'https://placeholder.com/800x300'" 
                  fit="cover"
                  class="project-banner"
                />
              </div>
              
              <h3 class="section-title">项目详情</h3>
              <div class="info-table">
                <div class="info-item">
                  <span class="label">主办方：</span>
                  <span class="value">{{ project.organizationName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">项目地点：</span>
                  <span class="value">{{ project.location }} ({{ project.fullAddress }})</span>
                </div>
                <div class="info-item">
                  <span class="label">开始时间：</span>
                  <span class="value">{{ new Date(project.date).toLocaleString() }}</span>
                </div>
                <div class="info-item">
                  <span class="label">结束时间：</span>
                  <span class="value">{{ new Date(project.endDate).toLocaleString() }}</span>
                </div>
                <div class="info-item">
                  <span class="label">持续时间：</span>
                  <span class="value">{{ Math.floor(project.duration / 60) }}小时{{ project.duration % 60 }}分钟</span>
                </div>
                <div class="info-item">
                  <span class="label">参与人数：</span>
                  <span class="value">{{ project.participantCount || 0 }}人</span>
                </div>
              </div>
              
              <h3 class="section-title">项目描述</h3>
              <div class="project-description">
                <p>{{ project.description }}</p>
              </div>
              
              <h3 class="section-title">项目地点</h3>
              <div class="location-section">
                <el-image
                  :src="project.locationImage || 'https://placeholder.com/600x300'"
                  class="location-image"
                />
              </div>
            </div>
          </el-col>

          <el-col :span="8">
            <div class="sidebar-section">
              <h3 class="section-title">我的参与情况</h3>
              <div class="participation-info">
                <div class="stat-item">
                  <div class="stat-icon"><el-icon><Calendar /></el-icon></div>
                  <div class="stat-content">
                    <div class="stat-value">{{ new Date(project.joinTime).toLocaleDateString() }}</div>
                    <div class="stat-label">报名时间</div>
                  </div>
                </div>
                <div class="stat-item">
                  <div class="stat-icon"><el-icon><Checked /></el-icon></div>
                  <div class="stat-content">
                    <div class="stat-value">{{ project.signInCount || 0 }}次</div>
                    <div class="stat-label">签到次数</div>
                  </div>
                </div>
                <div class="stat-item">
                  <div class="stat-icon"><el-icon><Timer /></el-icon></div>
                  <div class="stat-content">
                    <div class="stat-value">{{ Math.floor(project.myDuration / 60) }}小时{{ project.myDuration % 60 }}分钟</div>
                    <div class="stat-label">累计时长</div>
                  </div>
                </div>
                <div class="stat-item">
                  <div class="stat-icon"><el-icon><Star /></el-icon></div>
                  <div class="stat-content">
                    <div class="stat-value">{{ project.myRating ? `${project.myRating}分` : '暂未评价' }}</div>
                    <div class="stat-label">我的评价</div>
                  </div>
                </div>
              </div>
              
              <h3 class="section-title">签到记录</h3>
              <div class="sign-records">
                <el-empty v-if="!project.signRecords || project.signRecords.length === 0" description="暂无签到记录" />
                <el-timeline v-else>
                  <el-timeline-item
                    v-for="record in project.signRecords"
                    :key="record.id"
                    :timestamp="new Date(record.time).toLocaleString()"
                    :type="record.type === 'signIn' ? 'success' : 'info'">
                    {{ record.type === 'signIn' ? '签到' : '签退' }}
                    <template v-if="record.hours">
                      <span class="hours-tag">服务时长：{{ record.hours }}小时</span>
                    </template>
                  </el-timeline-item>
                </el-timeline>
              </div>
              
              <h3 class="section-title">快速操作</h3>
              <div class="quick-actions">
                <el-button 
                  v-if="project.status === 2"
                  type="success" 
                  @click="handleSign"
                  class="action-button">
                  <el-icon><Position /></el-icon> 立即签到
                </el-button>
                <el-button 
                  v-if="project.status === 2"
                  type="warning" 
                  @click="handleRecordHours"
                  class="action-button">
                  <el-icon><Timer /></el-icon> 登记时长
                </el-button>
                <el-button 
                  v-if="project.status === 3 && !project.myRating"
                  type="primary" 
                  @click="handleRate"
                  class="action-button">
                  <el-icon><Star /></el-icon> 评价项目
                </el-button>
                <el-button 
                  v-if="project.certificate"
                  type="info" 
                  @click="handleDownloadCertificate"
                  class="action-button">
                  <el-icon><Document /></el-icon> 下载证书
                </el-button>
                <el-button 
                  type="danger" 
                  @click="handleReport"
                  class="action-button">
                  <el-icon><Warning /></el-icon> 问题反馈
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 评价对话框 -->
    <el-dialog
      v-model="rateDialogVisible"
      title="项目评价"
      width="500px"
    >
      <el-form :model="rateForm" label-width="80px">
        <el-form-item label="评分">
          <el-rate
            v-model="rateForm.rating"
            :texts="['很差', '较差', '一般', '较好', '很好']"
            show-text
          />
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input
            v-model="rateForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入您的评价内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRate">提交评价</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 问题反馈对话框 -->
    <el-dialog
      v-model="reportDialogVisible"
      title="问题反馈"
      width="500px"
    >
      <el-form :model="reportForm" label-width="80px">
        <el-form-item label="问题类型">
          <el-select v-model="reportForm.type" placeholder="请选择问题类型">
            <el-option label="签到问题" value="sign" />
            <el-option label="时长问题" value="hours" />
            <el-option label="证书问题" value="certificate" />
            <el-option label="其他问题" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述">
          <el-input
            v-model="reportForm.content"
            type="textarea"
            :rows="4"
            placeholder="请详细描述您遇到的问题"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReport">提交反馈</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, Calendar, Checked, Timer, Star, 
  Position, Document, Warning
} from '@element-plus/icons-vue'
import { 
  getProjectDetail, 
  signInProject, 
  quitProject, 
  rateProject, 
  recordServiceHours,
  getProjectCertificate,
  submitProjectReport,
  joinProject
} from '@/api/volunteer-dashboard'

const route = useRoute()
const router = useRouter()
const projectId = route.params.id
const loading = ref(true)
const project = ref({
  title: '',
  description: '',
  organizationName: '',
  location: '',
  fullAddress: '',
  date: new Date(),
  endDate: new Date(),
  duration: 0,
  status: 0,
  auditStatus: 0,
  image: '',
  locationImage: '',
  participantCount: 0,
  myDuration: 0,
  signInCount: 0,
  myRating: null,
  joinTime: new Date(),
  signRecords: [],
  certificate: false
})

// 评价相关
const rateDialogVisible = ref(false)
const rateForm = ref({
  projectId: null,
  rating: 5,
  content: ''
})

// 问题反馈相关
const reportDialogVisible = ref(false)
const reportForm = ref({
  projectId: null,
  type: 'other',
  content: ''
})

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'info',    // 未开始
    1: 'warning', // 报名中
    2: 'success', // 进行中
    3: 'danger'   // 已结束
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '未开始',
    1: '报名中',
    2: '进行中',
    3: '已结束'
  }
  return texts[status] || '未知'
}

// 获取项目详情
const fetchProjectDetail = async () => {
  loading.value = true
  try {
    const res = await getProjectDetail(projectId)
    if (res.code === 200) {
      project.value = {
        ...res.data,
        signRecords: res.data.signRecords || [],
        myDuration: res.data.myDuration || 0,
        signInCount: res.data.signInCount || 0,
        myRating: res.data.myRating || null,
        joinTime: res.data.joinTime || new Date(),
        certificate: res.data.certificate || false
      }
    } else {
      ElMessage.error(res.message || '获取项目详情失败')
    }
  } catch (error) {
    ElMessage.error('获取项目详情失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 返回列表
const goBack = () => {
  router.push('/volunteer/projects')
}

// 签到/签退
const handleSign = async () => {
  try {
    const { value: type } = await ElMessageBox.confirm(
      '请选择签到类型',
      '签到',
      {
        distinguishCancelAndClose: true,
        confirmButtonText: '签到',
        cancelButtonText: '签退',
        type: 'info'
      }
    )
    
    const signType = type === 'confirm' ? 'signIn' : 'signOut'
    const res = await signInProject({
      projectId: project.value.id,
      type: signType
    })
    
    if (res.code === 200) {
      ElMessage.success(`已成功${signType === 'signIn' ? '签到' : '签退'}`)
      fetchProjectDetail()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('操作失败：' + (error.message || '未知错误'))
    }
  }
}

// 退出项目
const handleQuit = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要退出项目"${project.value.title}"吗？`,
      '退出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await quitProject(project.value.id)
    if (res.code === 200) {
      ElMessage.success(`已成功退出项目"${project.value.title}"`)
      router.push('/volunteer/projects')
    } else {
      ElMessage.error(res.message || '退出失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退出失败：' + (error.message || '未知错误'))
    }
  }
}

// 参与项目
const handleJoin = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要参与项目"${project.value.title}"吗？`,
      '参与确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    const res = await joinProject(project.value.id)
    if (res.code === 200) {
      ElMessage.success(`已成功报名参加项目"${project.value.title}"`)
      fetchProjectDetail()
    } else {
      ElMessage.error(res.message || '报名失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('报名失败：' + (error.message || '未知错误'))
    }
  }
}

// 登记服务时长
const handleRecordHours = async () => {
  try {
    const { value: form } = await ElMessageBox.prompt(
      '请输入本次服务时长（小时）',
      '登记服务时长',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[0-9]+(\.[0-9]{1,2})?$/,
        inputErrorMessage: '请输入正确的时长（如：2.5）',
        inputType: 'number',
        inputValue: '1'
      }
    )
    
    const res = await recordServiceHours({
      projectId: project.value.id,
      hours: parseFloat(form),
      date: new Date().toISOString().split('T')[0] // 默认使用当天日期
    })
    
    if (res.code === 200) {
      ElMessage.success('服务时长登记成功')
      fetchProjectDetail()
    } else {
      ElMessage.error(res.message || '登记失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('登记失败：' + (error.message || '未知错误'))
    }
  }
}

// 打开评价对话框
const handleRate = () => {
  rateForm.value = {
    projectId: project.value.id,
    rating: 5,
    content: ''
  }
  rateDialogVisible.value = true
}

// 提交评价
const submitRate = async () => {
  try {
    const res = await rateProject(rateForm.value)
    if (res.code === 200) {
      ElMessage.success('评价提交成功')
      rateDialogVisible.value = false
      fetchProjectDetail()
    } else {
      ElMessage.error(res.message || '评价提交失败')
    }
  } catch (error) {
    ElMessage.error('评价提交失败：' + (error.message || '未知错误'))
  }
}

// 下载证书
const handleDownloadCertificate = async () => {
  try {
    const res = await getProjectCertificate(project.value.id)
    if (res) {
      const blob = new Blob([res], { type: 'application/pdf' })
      const downloadLink = document.createElement('a')
      downloadLink.href = URL.createObjectURL(blob)
      downloadLink.download = `${project.value.title}_证书.pdf`
      document.body.appendChild(downloadLink)
      downloadLink.click()
      document.body.removeChild(downloadLink)
    } else {
      ElMessage.error('证书下载失败')
    }
  } catch (error) {
    ElMessage.error('证书下载失败：' + (error.message || '未知错误'))
  }
}

// 打开问题反馈对话框
const handleReport = () => {
  reportForm.value = {
    projectId: project.value.id,
    type: 'other',
    content: ''
  }
  reportDialogVisible.value = true
}

// 提交问题反馈
const submitReport = async () => {
  try {
    const res = await submitProjectReport(reportForm.value)
    if (res.code === 200) {
      ElMessage.success('反馈提交成功')
      reportDialogVisible.value = false
    } else {
      ElMessage.error(res.message || '反馈提交失败')
    }
  } catch (error) {
    ElMessage.error('反馈提交失败：' + (error.message || '未知错误'))
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchProjectDetail()
})
</script>

<style scoped lang="scss">
.project-detail-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;

      .project-title {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #303133;
      }

      .status-tag {
        margin-left: 8px;
      }
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .project-content {
    padding: 20px 0;

    .project-banner {
      width: 100%;
      height: 300px;
      border-radius: 8px;
      margin-bottom: 24px;
    }

    .section-title {
      font-size: 18px;
      font-weight: 600;
      margin: 24px 0 16px;
      padding-left: 12px;
      border-left: 4px solid #409EFF;
      line-height: 1.5;
    }

    .info-table {
      background: #f9f9f9;
      border-radius: 8px;
      padding: 16px;
      
      .info-item {
        margin-bottom: 12px;
        display: flex;
        align-items: baseline;
        
        .label {
          width: 100px;
          color: #606266;
          font-size: 14px;
        }
        
        .value {
          flex: 1;
          color: #333;
          font-size: 14px;
        }
      }
    }

    .project-description {
      line-height: 1.8;
      color: #606266;
      font-size: 14px;
      margin-bottom: 24px;
    }

    .location-image {
      width: 100%;
      height: 200px;
      border-radius: 8px;
      margin-top: 12px;
    }

    .sidebar-section {
      background: #fff;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 20px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

      .participation-info {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
        margin-bottom: 24px;

        .stat-item {
          display: flex;
          align-items: center;
          gap: 12px;

          .stat-icon {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            background: #ecf5ff;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #409EFF;
          }

          .stat-content {
            .stat-value {
              font-size: 16px;
              font-weight: 500;
              color: #303133;
              line-height: 1.4;
            }

            .stat-label {
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }

      .sign-records {
        min-height: 160px;
        margin-bottom: 24px;
      }

      .quick-actions {
        display: flex;
        flex-direction: column;
        gap: 12px;
      }
    }
  }

  .hours-tag {
    margin-left: 8px;
    padding: 2px 6px;
    background: #f0f9eb;
    color: #67c23a;
    border-radius: 4px;
    font-size: 12px;
  }
}
</style> 